const { app, BrowserWindow, Menu, Tray, nativeImage} = require('electron')
const express = require('express')
var cors = require('cors')
var http = require('http')
var bodyParser = require('body-parser');
const fs = require('fs')
const path = require('path')
const os = require('os')


//http 服务
function createServer(){
  var web = express();
  var port = 2023
  //var router = express.Router();
  web.set('port', port);
  web.use(bodyParser.json({limit: '50mb'}));
  web.use(bodyParser.urlencoded({limit: '50mb', extended: true}));
  //web.use('/', router);
  web.use(cors(
    {origin: '*'}
  ))
  var server = http.createServer(web);
  server.listen(port);

  web.get('/*', function (req, res, next) {
    res.end()
  })

  //export PDF
  web.post('/pdf/*', function (req, res, next) {

    if(req.body && req.body.html){
      let html = req.body.html
      let temp = path.join(__dirname, '_temp.html')
      fs.writeFile(temp, html, (err) => {
        if(err){
          res.end(JSON.stringify(err))
        }else{
          app.win.loadFile(temp).then(()=> {
            let option = defaultPrintOption()
            app.win.webContents.printToPDF(option).then(data => {
              res.send(data)
            })
          }).catch(e =>{
            res.end(JSON.stringify(e))
          })
        }
      })
    }else{
      res.end()
    }
  })

  //服务请求
  web.post('/print/*', function (req, res, next) {

    if(req.body && req.body.data){
      let html = req.body.data
      let temp = path.join(__dirname, '_temp.html')
      fs.writeFile(temp, html, (err) => {
        if(err)console.error(err)
      })
      app.win.loadFile(temp).then(function(){
        if(req.originalUrl.endsWith('direct')){
          printToDefault()
        }else{
          printToPDF(app.win.webContents.getTitle())
        }
        res.end()
      }).catch(function(e){
        res.end()
      })
    }
  })
}

//创建主窗口
function createWindow () {
  const win = new BrowserWindow({
    width: 800,
    height: 600,
    autoHideMenuBar: true,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js')
    }
  })
  return win;
}

//窗口菜单
function createMenu(){
  const template = [
    {label: 'Debug', submenu: [
      {label: 'printToDefault', click: printToDefault},
      {label: 'printToPDF', click: printToPDF},
      {label: 'showDevelop', click: ()=>app.win.webContents.openDevTools()},
    ]}
  ]

  const menu = Menu.buildFromTemplate(template)
  Menu.setApplicationMenu(menu)
}

//系统托盘
function createTray(){
  let path = './static/icon.png'
  if(!fs.existsSync(path)){
    path = './resources/app/static/icon.png'
  }
  const icon = nativeImage.createFromPath(path)
  let tray = new Tray(icon)
  const contextMenu = Menu.buildFromTemplate([
    {label: '打印预览', click:(e)=>{
      if(app.win.isVisible()){
        app.win.hide()
      }else{
        app.win.show()
      }
  
    }},
    {label: '退出', click:()=>{
      app.win.requestQuit = true
      app.quit()
    }},
  ])
  
  tray.setContextMenu(contextMenu)
  tray.setToolTip('X-Printer')
  tray.setTitle('打印驱动')
  
}

function defaultPrintOption(){
  return {
    silent: true,
    margins:{top:0, bottom:0, left:0, right:0},
    preferCSSPageSize: true,
  }
}

//打印
function printToDefault(){
  let option = defaultPrintOption()
  app.win.webContents.getPrintersAsync().then((printers)=>{
    printers.forEach(p => {
        if(p.isDefault){
          option.defaultPrinter =  p.name
        }
    })
  })
  
  app.win.webContents.print(option, (success, errorType) => {
    if (!success) console.log(errorType)
  })
}

//print PDF
function printToPDF(title){
  let option = defaultPrintOption()
  if(!title) title = new Date().getTime()
  const pdfPath = path.join(os.homedir(), 'Desktop', title +'.pdf')
  app.win.webContents.printToPDF(option).then(data => {
    fs.writeFile(pdfPath, data, (error) => {
      if (error) throw error
      console.log(`Wrote PDF successfully to ${pdfPath}`)
    })
  }).catch(error => {
    console.log(`Failed to write PDF to ${pdfPath}: `, error)
  })
}

//内容更新
function webFinishLoad(e){
  let url = app.win.webContents.getURL()
  if(url.endsWith('temp.html')){
  }
}

//启动
app.whenReady().then(() => {
  createServer()
  createTray()
  createMenu()
  app.win = createWindow()
  app.win.hide()
  app.win.loadFile('index.html')
  app.win.webContents.on('did-finish-load', webFinishLoad)
  app.win.on('close',(e) => {
    if(!app.win.requestQuit){
      e.preventDefault()
      app.win.hide()
    }
  })
  app.win.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
      app.win= createWindow()
    }
  })
})
